package logic

import (
	"context"
	"fmt"
	"vipshop-app/models/cache"
	"vipshop-app/models/mysql"
	"vipshop-app/pkg"

	"vipshop-app/vipshopapc/internal/svc"
	"vipshop-app/vipshopapc/vipshopapc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *vipshopapc.LoginRequest) (*vipshopapc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	getImage := cache.Rdb.Get(l.ctx, "captcha"+"login"+in.Mobile)
	if getImage.Val() != in.Captcha {
		return nil, fmt.Errorf("图形验证码错误,请重新输入")
	}

	getSms := cache.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
	if getSms.Val() != in.Captcha {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在，请先注册")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码输入错误,请重新输入")
	}

	//成功后删除短信缓存
	cache.Rdb.Del(l.ctx, "captcha"+"login"+in.Mobile)
	cache.Rdb.Del(l.ctx, "sendSms"+"login"+in.Mobile)
	return &vipshopapc.LoginResponse{Id: int64(user.ID)}, nil
}
